package top.ajunnihao.core.web.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * TODO 验证码控制器
 *
 * @author AJun
 * @version 1.0.0
 * @date 2020/5/25
 */
@Controller
@RequestMapping("/captcha")
public class CaptchaController {

    private static final String CAPTCHA_CODE = "CAPTCHA_CODE";

    /**
     * 验证码生成服务
     */
    @RequestMapping("/generate")
    public void generated(HttpServletResponse response, HttpSession session) throws IOException {
        // 设置浏览器ContentType，禁止浏览器缓存，使验证码可以访问一次便刷新一次
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("expires", -1);

        // 生成验证码并写出
        // 100宽，50高，4个字符验证码，20个圆形干扰线
        ICaptcha captcha = CaptchaUtil.createLineCaptcha(100, 38, 4, 15);
        // 获取验证码内容，写入到 session
        session.setAttribute(CAPTCHA_CODE, captcha.getCode());
        // 将验证码写出
        captcha.write(response.getOutputStream());
    }

}
